package org.iabako.server.servlet;

import org.iabako.server.serviceimpl.security.SessionUser;
import org.iabako.shared.entity.enumeration.Language;
import org.iabako.shared.iservice.user.SignUpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by jose on 05/12/14.
 */
public class ChangeLanguageServlet extends HttpServlet {

    @Autowired
    SignUpService signUpService;
    @Autowired
    SessionUser sessionUser;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String langParameter = req.getParameter("lang");

        for (Language language : Language.values()) {
            if (language.getLangString().equalsIgnoreCase(langParameter)) {
                Cookie cookie = new Cookie("IABAKO_LANG", language.getLangString());
                //cookie expiration in about 10 years
                cookie.setMaxAge(60 * 60 * 24 * 365 * 10);
                resp.addCookie(cookie);

                req.getSession().setAttribute("IABAKO_LANG", language);

                if (sessionUser != null && sessionUser.getUser() != null
                        && sessionUser.getUser().getEnterprise() != null
                        && !sessionUser.getUser().getEnterprise().isDemo()) {

                    sessionUser.getUser().getEnterprise().setLanguage(language);
                    signUpService.saveEnterprise(sessionUser.getUser().getEnterprise());
                }

                return;
            }
        }
    }
}
